import Vue from 'vue'
/**
 * 适用于元素边框拖动
 */
let isDown = false
let left,top = 0
let $el
function td(e){
  const left = document.getElementsByClassName('sidebar-container')[0].offsetWidth || 0
  if( $el.style.cursor === 'se-resize'){
    $el.style.width = e.clientX - $el.offsetLeft - left + 'px'
    $el.style.height = e.clientY - $el.offsetTop + 'px'
  }else if($el.style.cursor === 'e-resize'){
    $el.style.width = e.clientX - $el.offsetLeft- left + 'px'
  }else if($el.style.cursor === 's-resize'){
    $el.style.height = e.clientY - $el.offsetTop + 'px'
  }
}
function wup(e){
  $el.style.cursor = 'default'
  window.removeEventListener('mousemove',td)
  window.removeEventListener('mouseup',wup)
  isDown = false
}
function borderMove(e,el){
  if(el.style.cursor === 'se-resize' || el.style.cursor === 'e-resize' || el.style.cursor === 's-resize'){
    isDown = true
    $el = el
    window.addEventListener('mousemove',td)
    window.addEventListener('mouseup',wup)
  }
}
//添加边缘判断事件
function isBorder(e,el){
  if(!isDown){
    const left = document.getElementsByClassName('sidebar-container')[0].offsetWidth || 0
    const right =  el.offsetWidth + el.offsetLeft - e.clientX
    const bottom = el.offsetHeight + el.offsetTop - e.clientY
    if(right < 10 && bottom < 10){
      el.style.cursor = 'se-resize'
    }else if(right < 10){
      el.style.cursor = 'e-resize'
    }else if(bottom < 10){
      el.style.cursor = 's-resize'
    }else{
      el.style.cursor = 'default'
    }
  }
}

const borderDrag ={
  install:function(){
    Vue.directive('borderDrag',{
      inserted:function(el, binding, vnode, oldVnode){
        el.addEventListener('mousemove',(e)=>isBorder(e,el))
        el.addEventListener('mousedown',(e)=>borderMove(e,el))
      }
    })
  }
}
export default borderDrag
